package array;

/**
 * Created by fengliejv on 2017/11/22.
 */
public class SingleElementinaSortedArray540 {
    //todo
    public int singleNonDuplicate(int[] nums) {
        int left = 0;
        int right = nums.length - 1;
        if (nums.length == 1) {
            return nums[0];
        }
        while (left <= right) {
            int mid = (right - left) / 2 + left;
            if (mid == 0 && nums[mid] != nums[mid + 1]) {
                return nums[mid];

            }
            if (mid == nums.length - 1 && nums[mid - 1] != nums[mid]) {
                return nums[mid];
            }
            if(mid==0){
                left=mid+1;
            }else if(mid==nums.length-1){
                right = mid-1;
            }else if (nums[mid] != nums[mid - 1] && nums[mid] != nums[mid + 1]) {
                return nums[mid];
            }
            if (nums[mid] == nums[mid + 1] && mid % 2 != 0) {
                right = mid - 1;
            }
            if (nums[mid] == nums[mid + 1] && mid % 2 == 0) {
                left = mid + 2;
            }
            if (nums[mid] == nums[mid - 1] && (mid - 1) % 2 != 0) {
                right = mid - 2;
            } else {
                left = mid + 1;
            }
        }
        return 0;
    }
//    public int singleNonDuplicate(int[] nums) {
//        int res=0;
//        for (int i = 0; i < nums.length; i++) {
//            res^=nums[i];
//        }
//        return res;
//    }
}
